<template>
  <div id="applyVSReport">
    <Breadcrumb content="标本细菌检出情况" />
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <el-form :model="searchForm" class="form-input-m" label-width="80px" :inline="true">
            <el-form-item label="报告单元">
              <SelectWorkGroupAllDefaultAll ref="selectWorkGroupRef" :url="'/api/rptGroup/findRptGroup'"
                :inputWidth="'100%'" @fatherMethod="searchWklt" :isShowAll="true" :isClear="true">
              </SelectWorkGroupAllDefaultAll>
            </el-form-item>
            <el-form-item label="统计日期">
              <el-date-picker v-model="searchForm.countTime" value-format="YYYY-MM-DD" type="daterange"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="查询"
                @click="getLyReagent"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-print" content="打印"
                @click="getLyReagent"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-download" content="导出（标本类型）统计"
                @click="exportExcel('#printTest', '（标本类型）统计', 1)"></vxe-button>&nbsp;&nbsp;
              <vxe-button type="text" class="button-green" icon="vxe-icon-download" content="导出（标本类型）统计明细"
                @click="exportExcel('#printTest', '（标本类型）统计明细', 2)"></vxe-button>
            </el-form-item>
            <el-row>
              <!--              <el-form-item label="细菌组" prop="germType">
                <SelectDataList ref="employeeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :displayField="[
                { title: '编码', props: 'code' }, //列标题
                { title: '名称', props: 'name' }
              ]" :placeholder="'点击选择细菌组'" :searchParam="{ code: 'germType' }" @selectDataRow="SelectRowClick" @clearValue="germTypeClear" v-model="searchForm.germType" />
              </el-form-item>-->
              <el-form-item label="细菌">
                <SelectDataList ref="employeeSelectRef" :url="'/bac/germ/dict/getGermsByParams'" :displayField="[
                  { title: '编码', props: 'germNo' }, //列标题
                  { title: '名称', props: 'germNa' }
                ]" :placeholder="'点击选择细菌'" :searchParam="{ code: 'bacteria' }" @clearValue="clearValueHandler3"
                  @selectDataRow="SelectRowClick3" v-model="searchForm.bacteria" />
              </el-form-item>
              <el-form-item label="耐药表型">
                <VxePulldownMultiSelection ref="cleanFeeItemSelection" childIndex="fee"
                  url="/lis/bac/base/resistant-phenotype/dict/findDictList"
                  @confirmClick="(data) => resiPhenList(data, 'resiPhen')" :tableColumn="[
                    { field: 'code', title: '编号' },
                    { field: 'name', title: '名称' }
                  ]" :displayTexts="['name']" :displayTextObj="searchForm.resiPhenName"
                  :dicValues="searchForm.resiPhens" includeVal="id" v-model="searchForm.resiPhenName" />
              </el-form-item>
              <el-form-item label="去除重复" prop="color">
                <template #default>
                  <el-checkbox v-model="searchForm.isDistinct" :true-label="1" :false-label="0"
                    @click="getLyReagent"></el-checkbox>
                </template>
              </el-form-item>
            </el-row>
          </el-form>
        </template>
      </vxe-toolbar>
      <Splitpanes>
        <!-- class="area" -->
        <Pane :size="40">
          <div class="leftTable">
            <vxe-table :loading="feeItemShowLoading" ref="feeitemVsItemdictTable" border class="mytable-scrollbar" height="auto" show-header-overflow
              show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" @current-change="instrRowClick"
              :data="feeitemVsItemdictList" :edit-config="{ trigger: 'click', mode: 'cell' }"
              :column-config="{ resizable: true }" :sort-config="{ trigger: 'cell', defaultSort: { field: 'total', order: 'rsce' } }">
              <!-- <vxe-column type="checkbox" width="30px" align="center"></vxe-column> -->
              <vxe-column type="seq" title="#" width="30"></vxe-column>
              <vxe-column field="name" title="标本类型" width="150"></vxe-column>
              <vxe-column field="total" title="总数" sortable></vxe-column>
              <vxe-column field="yang" title="阳性数" width="100"></vxe-column>
              <vxe-column field="rate" title="阳性率(%)" width="60"></vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <!-- 右侧信息 -->
        <Pane :size="60">
          <vxe-toolbar perfect>
            <template #buttons>
              当前试剂条码号：{{ sampleTypeName }}
            </template>
          </vxe-toolbar>
          <div class="rightTable">
            <vxe-table ref="itemDictTable" border show-header-overflow height="auto" show-overflow align="left"
              :row-config="{ isCurrent: true, isHover: true }" :data="itemDictList" :loading="showLoading"
              class="mytable-scrollbar" :sort-config="{ trigger: 'cell', defaultSort: { field: 'total', order: 'rsce' } }">
              <vxe-column type="seq" title="#" width="30"></vxe-column>
              <vxe-column field="code" title="代号" width="100">
              </vxe-column>
              <vxe-column field="name" title="细菌" width="200">
              </vxe-column>
              <vxe-column field="total" title="数量" width="80" sortable>
              </vxe-column>
              <vxe-column field="rate" title="比例（%）">
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { ref, reactive, getCurrentInstance, onMounted, watch } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';
import SelectWorkGroupAllDefaultAll from '../lab_bus/components/SelectWorkGroupAllDefaultAll.vue'; //报告单元默认全部引入下拉组件
import VxePulldownMultiSelection from '@/components/VxePulldownMultiSelection.vue';
import { GetRptGroupOptions } from '@/utils/SysOptionsHelper';
import SelectDataList from '../../../components/SelectDataList.vue';
import { IsEmpty } from '@/utils/common';
import VXETable from 'vxe-table';
import moment from 'moment';

let store = AppStore();
// 全局变量定义区 ==========
// 变量定义区
let { proxy }: any = getCurrentInstance();
let conWidth = ref(document.documentElement.clientWidth);
const itemDictList = reactive([]);
let selevctFeeItemRow: any = reactive({
  id: ''
});

let showLoading = ref(false); //刷新+表格加载
let feeItemShowLoading = ref(false);
let searchValue = ref('');
const searchForm = reactive({
  orgId: store.userInfo.orgId,
  countTime: [],
  name: store.userInfo.orgName,
  reagentSearchValue: '',
  bacteria: '',
  rptGroup: '',
  resiPhenName: '',
  resiPhenCodes: [],
  resiPhens: [],
  germType: '',
  isDistinct: 0,
});
let instrSetupList = reactive([]); //仪器列表
let addDialog = ref(false); //添加弹框展示状态
let loading = ref(false); //添加弹框展示状态
let rowData = ref({}); //当前行数据
let instrCode = ref('');
let hrForm = reactive({
  id: '',
  openCloseTime: ''
});
let sampleTypeName = ref(null);
let cleanFeeItemSelection = ref(null);
const feeitemVsItemdictList = reactive([]);
// 方法定义区 =============
onMounted(() => {
  getLyReagent();
});

function resiPhenList(data, keyName) {
  searchForm[keyName + 's'] = [];
  searchForm[keyName + 'Ids'] = [];
  searchForm[keyName + 'Codes'] = [];
  searchForm[keyName + 'Name'] = '';
  if (IsEmpty(data.aimKeys) || data.aimKeys.length === 0) {
    const arr = data.arr;
    searchForm[keyName + 's'] = arr;
    if (arr.length !== 0) {
      arr.forEach((item) => {
        if (item.id) {
          searchForm[keyName + 'Ids'].push(item.id);
          searchForm[keyName + 'Codes'].push(item.code);
        } else {
          searchForm[keyName + 'Ids'].push(item.code);
        }
        if (item.name) {
          searchForm[keyName + 'Name'] += item.name + ',';
        } else if (item[keyName + 'Name']) {
          searchForm[keyName + 'Name'] += item[keyName + 'Name'] + ',';
        } else {
          searchForm[keyName + 'Name'] += item.realname + ',';
        }
      });

      if (searchForm[keyName + 'Name'] && searchForm[keyName + 'Name'].trim()) {
        searchForm[keyName + 'Name'] = searchForm[keyName + 'Name'].slice(0, -1);
      }
    }
  } else {
    data.arr.forEach((item) => {
      data.aimKeys.forEach((val) => {
        searchForm[val.targetField + 's'].push(item);
        searchForm[val.targetField + 'Ids'].push(item[val.targetField + 'Id']);
        searchForm[val.targetField + 'Name'] += item[val.targetField].name + ',';
      });
    });
  }
}

function SelectRowClick(row) {
  console.log(row);
  //formData.germType = row.code;
  searchForm.germType = row.name;
}
function SelectRowClick3(row) {
  searchForm.bacteria = row.germNo;
  getLyReagent();
}
// 清空组件输入框
function clearValueHandler3() {
  searchForm.bacteria = '';
  getLyReagent();
}
//获取工作列表
function searchWklt(selectedRadioId, selectedName) {
  searchForm.rptGroup = selectedRadioId.value;
}

function instrRowClick({ row }: any) {
  (proxy.$refs.feeitemVsItemdictTable as any).setCurrentRow(row);
  sampleTypeName.value = row.name;
  getOpenEmptyBoxList();
}

function getOpenEmptyBoxList() {
  findOpenEmptyBoxList(selevctFeeItemRow);
}

// 获取报告项目列表
function findOpenEmptyBoxList(row: any) {
  itemDictList.length = 0;
  showLoading.value = true;
  const url = '/bac_count/findBacSpecimenDetial';
  let obj = {
    params: {
      startTime: (searchForm.countTime ? searchForm.countTime[0] : null),
      endTime: (searchForm.countTime ? searchForm.countTime[1] : null),
      rptGroup: searchForm.rptGroup,
      sampleTypeName: sampleTypeName.value,
      isDistinct : searchForm.isDistinct
    }
  };
  proxy.$http
    .get(url, obj)
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        itemDictList.push(...res.data);
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      showLoading.value = false;
    });
}

// 获取中间的报告单元信息
function getLyReagent() {
  feeitemVsItemdictList.length = 0;
  feeItemShowLoading.value = true;
  const url = '/bac_count/findBacSpecimenCountDistinct';
  let obj = {
    params: {
      startTime: (searchForm.countTime ? searchForm.countTime[0] : null),
      endTime: (searchForm.countTime ? searchForm.countTime[1] : null),
      rptGroup: searchForm.rptGroup,
      resiPhenCodes: searchForm.resiPhenCodes.join(','),
      bacteria: searchForm.bacteria,
      germType: searchForm.germType,
      orgId: searchForm.orgId,
      isDistinct : searchForm.isDistinct
    }
  };
  proxy.$http
    .get(url, obj)
    .then((res: any) => {
      if (res && res.data && res.data.length > 0) {
        feeitemVsItemdictList.push(...res.data);
        if (feeitemVsItemdictList.length > 0) {
          const kn = feeitemVsItemdictList.find((k) => k.id == selevctFeeItemRow.id);
          if (isEmpty(kn)) {
            instrRowClick({ row: feeitemVsItemdictList[0] });
          } else {
            instrRowClick({ row: kn });
          }
        } else {
          selevctFeeItemRow.id = '';
        }
      } else {
        itemDictList.length = 0;
        selevctFeeItemRow.id = '';
      }
      feeItemShowLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      feeItemShowLoading.value = false;
    });
}

//导出excel
function exportExcel(dom, title, type) {
  if (type == 1) {
    const $table = proxy.$refs.feeitemVsItemdictTable as any;
    $table.exportData({ data: feeitemVsItemdictList, type: 'csv', filename: title, useStyle: true });
  } else {
    const $table = proxy.$refs.itemDictTable as any;
    $table.exportData({ data: itemDictList, type: 'csv', filename: title, useStyle: true });
  }
}
</script>
<style lang="scss" scoped>
#applyVSReport {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;
    }

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
  }

  .splitpanes {
    background-color: $base-white;
    height: calc(100% - 90px);
  }

  :deep(.splitpanes__pane) {
    overflow: visible;
  }

  .dialogFooter {
    text-align: right;
  }

  .rightTable {
    height: calc(100% - 12px);
  }

  .leftTable {
    height: calc(100% - 0px);
  }
}</style>
